package D240529;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class FileUtil {
    private static final Map<String, Integer> FILE_TYPE_COUNTS = new HashMap<>();
    private static StringBuilder structureSymbol = new StringBuilder();

    public static void main(String[] args) {
        File directory = new File("src");
        showTreePrint(directory,0);
        //showTreeStructure(directory);
        // countFileTypes(directory);
        /*for (Map.Entry<String, Integer> entry : FILE_TYPE_COUNTS.entrySet()) {
            System.out.println("类型：" + entry.getKey() + "，数量：" + entry.getValue() + " 个");
        }*/
    }

    private static void countFileTypes(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    countFileTypes(file);
                } else {
                    String ext = getFileExtension(file.getName());
                    if (FILE_TYPE_COUNTS.containsKey(ext)) {
                        FILE_TYPE_COUNTS.put(ext, FILE_TYPE_COUNTS.get(ext) + 1);
                    } else {
                        FILE_TYPE_COUNTS.put(ext, 1);
                    }
                }
            }
        }
    }

    private static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex == -1 ? "无后缀" : fileName.substring(lastDotIndex + 1);
    }

    private static void showTreeStructure(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    System.out.println(structureSymbol + file.getName());
                    structureSymbol.append("--");
                    showTreeStructure(file);
                } else {
                    long length = file.length() / 1024;
                    System.out.println(structureSymbol + file.getName() + "(" + length + "KB)");
                }
            }
            structureSymbol.setLength(0);
        }
    }

    private static void showTreePrint(File directory,int level) {
        for (int i = 0; i < level; i++) {
            System.out.print("--");
        }
        System.out.println(directory.getName());
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File f : files)
                showTreePrint(f , level+1);
                ;
            }
        }
    }
}
